package cn.itcast.delay.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * @author 虎哥
 */
@Configuration
public class RedisConfig {
    /**
     * 配置Redis消息监听器的容器
     */
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        return container;
    }

    /**
     * 配置一个过期key的消息监听器
     */
    @Bean
    public KeyExpirationEventMessageListener redisKeyExpirationListener(RedisMessageListenerContainer container){
        // 创建监听器，覆盖监听器默认的doHandleMessage方法
        return new KeyExpirationEventMessageListener(container){
            @Override
            protected void doHandleMessage(Message message) {
                // 获取消息体
                byte[] body = message.getBody();
                // 获取消息类型
                byte[] channel = message.getChannel();
                // 输出
                System.out.println("body = " + new String(body));
                System.out.println("channel = " + new String(channel));
            }
        };
    }
}